package com.haois.mp.database.module.wxserver.service;

import com.haois.mp.database.commom.enums.MpTypeEnum;
import com.haois.mp.database.module.common.daomain.WxUser;
import com.haois.mp.database.module.offaccounts.service.UserFollowService;
import com.haois.mp.database.util.jx.DateUtil;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by RuiHaoZ on 2018/2/1 0:47
 */
@Service
public class WxUserService {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private UserFollowService userFollowService;


    public List<WxMpUser> syncWxUser() throws WxErrorException {
        WxMpUserList result = wxMpService.getUserService().userList(null);
        List<WxMpUser> wxMpUsers = new ArrayList<>();
        for (String openId : result.getOpenids()) {
            WxMpUser wxMpUser = syncWxUser(openId);
            if (wxMpUser != null) {
                wxMpUsers.add(wxMpUser);
            }
        }
        return wxMpUsers;
    }

    public List<WxMpUser> syncWxUserByDB() throws WxErrorException {
        List<WxUser> wxUsers = userFollowService.getBySubState(MpTypeEnum.OFFACCOUNTS.getType());
        List<WxMpUser> wxMpUsers = new ArrayList<>();
        for (WxUser wxUser : wxUsers) {
            WxMpUser wxMpUser = syncWxUser(wxUser.getOpenId());
            wxMpUsers.add(wxMpUser);
        }
        return wxMpUsers;
    }

    public WxMpUser syncWxUser(String openId) {
        WxMpUser wxMpUser = null;
        try {
            wxMpUser = wxMpService.getUserService().userInfo(openId);
        } catch (WxErrorException e) {
            WxUser wxUser = new WxUser();
            wxUser.setOpenId(openId);
            wxUser.setRemark(e.getError().getErrorMsg());
            wxUser.setSubscribeState("0");
            wxUser.setUpdateTime(DateUtil.getYMdHm());
            userFollowService.syncWxMpUser(wxUser);
            return wxUser;
        }
        WxUser wxUser = userFollowService.getByOpenId(openId, MpTypeEnum.OFFACCOUNTS.getType());
        if (wxUser == null) {
            wxUser = new WxUser(wxMpUser);
            wxUser.setSubscribeState(wxMpUser.getSubscribe() ? "1" : "0");
            wxUser.setRemark("系统同步添加");
            userFollowService.subscribe(wxUser);
        } else {
            if (wxMpUser.getSubscribe()) {
                wxUser = new WxUser(wxMpUser);
            }
            wxUser.setSubscribeState(wxMpUser.getSubscribe() ? "1" : "0");
            wxUser.setRemark("系统同步修改");
            wxUser.setUpdateTime(DateUtil.getYMdHm());
            userFollowService.syncWxMpUser(wxUser);
        }
        return wxMpUser;
    }
}
